/**
* coder  : dzlua
* email  : 505544956@qq.com
* module : ApiMgr-client
* path   : src/api
* file   : request.js
* time   : 2017-11-20 18:02:00
*/

// 配置API接口地址
const root = '/api'
// 引用axios
let axios = require('axios')

/*
  {
    url: url,
    params: params,
    username,
    password,
    token,
    method: method || 'POST'
  }
*/
function request (config, success, failure) {
  let method = config.method || 'POST'
  let headers = {}

  if (config.token) {
    headers.Authorization = 'Bearer ' + config.token
  } else if (config.username && config.password) {
    headers.Authorization = 'Basic ' + Buffer.from(
        config.username + ':' + config.password
      ).toString('base64')
  }

  axios({
    url: config.url,
    method: method,
    baseURL: root,
    data: method === 'POST' ||
          method === 'PUT' ? config.params : null,
    params: method === 'GET' ||
          method === 'DELETE' ? config.params : null,
    headers: headers,
    withCredentials: false
  })
  .then(resp => {
    if (resp.data.success === true) {
      if (success) {
        success(resp.data)
      }
    } else {
      if (failure) {
        failure(resp.data)
      } else {
        window.alert('API ERROR: ' + JSON.stringify(resp.data))
      }
    }
  })
  .catch(err => {
    if (failure) {
      failure(err.response.data)
    } else {
      window.alert('API ERROR: ' + JSON.stringify(err.response.data))
    }
  })
}

// 返回在vue模板中的调用接口
export default {
  request: request,
  req: function (config, callback) {
    return request(config, callback, callback)
  }
}
